#include "ui.h"

#include "SDL_ttf.h"
#include <assert.h>
#include <config.h>
#include <stdarg.h>

#include "global.h"
#include "cursors.h"
#include "data.h"
#include "images.h"
#include "palette.h"
#include "text.h"


// Initialize everything related to the UI.
void ui_init()
{
	// Initialize SDL
	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_NOPARACHUTE) == -1)
	{
		fprintf(stderr, _("Could not initialize SDL: %s\n"), 
				SDL_GetError());
		exit(2);
	}

	atexit(SDL_Quit);

	// Create SDL window
	SDL_Surface *icon = SDL_LoadBMP(datapath("citymanager.bmp"));
	if(icon)
	{
		SDL_SetColorKey(icon, SDL_SRCCOLORKEY, 1);
		SDL_WM_SetIcon(icon, NULL);
	}
	screen = SDL_SetVideoMode(1000, 700, 8, SDL_SWSURFACE|SDL_RESIZABLE);
	if(!screen)
	{
		fprintf(stderr, _("Could not initialize SDL window: %s\n"),
				SDL_GetError());
		exit(2);
	}

	// Initialize SDL_ttf
	if(TTF_Init() == -1)
	{
		fprintf(stderr, _("Could not initialize SDL_ttf: %s\n"),
				TTF_GetError());
		exit(2);
	}

	// Load first error font
	font_error = TTF_OpenFont(datapath("error.ttf"), 16);
	if(!font_error)
	{
		fprintf(stderr, _("Could not load font error.ttf: %s\n"), 
					TTF_GetError());
		exit(2);
	}

	// Initialize SDL_image
	if(IMG_Init(IMG_INIT_PNG) != IMG_INIT_PNG)
	{
		ui_error(_("Could not initialize SDL_Image: %s"), IMG_GetError());
		exit(2);
	}

	// Set WM information
	SDL_WM_SetCaption(PACKAGE " " VERSION, PACKAGE " " VERSION);

	// Load everything
	init_cursors();
	init_palette();
	load_fonts();
	load_images();
}


// Display a error message in the screen and exit.
void ui_error(const char *fmt, ...)
{
	char buffer[1024];

	// create error string
	va_list args;
	va_start(args, fmt);
	vsprintf(buffer, fmt, args);
	va_end(args);

	// if screen not available, write to strerr
	fprintf(stderr, "%s\n", buffer);
	assert(font_error);

	// display on the screen
	SDL_FillRect(screen, NULL, BLACK);
	SDL_Surface* text = TTF_RenderUTF8_Solid(font_error, buffer, 
			(SDL_Color){255, 255, 255});
	if(!text)
	{
		fprintf(stderr, "%s\n", buffer);
		exit(2);
	}

	SDL_Rect r = { (screen->w/2 - text->w/2), (screen->h/2 - text->h/2) };
	SDL_BlitSurface(text, NULL, screen, &r); // TODO
	SDL_Flip(screen);
	SDL_FreeSurface(text);

	// wait for keypress
	SDL_Event e;
	while(1)
	{
		SDL_WaitEvent(&e);
		if(e.type == SDL_KEYDOWN || e.type == SDL_QUIT)
			exit(2);
	}
}


// Main game loop. Updates the screen and process events.
void ui_main_loop()
{
	SDL_Event e;
	_Bool running = true;
	Uint32 n_frame = 0;

	while(running)
	{
		Uint32 next_frame = SDL_GetTicks() + (1000 / 60);

		// update video
		ui_update_video();

		// process events
		while(SDL_PollEvent(&e))
			switch(e.type)
			{
				// user resizes window
				case SDL_VIDEORESIZE:
					screen = SDL_SetVideoMode(e.resize.w, 
							e.resize.h, 8, 
							screen->flags);
					setup_palette(screen);
					ui_update_video();
					break;

				// user clicks on "X"
				case SDL_QUIT:
					// TODO - save city
					running = false;
					break;
			}

		// process, and wait time for the next frame, where
		//   * paused: doesn't process at all
		//   * slow: process every 3 frames
		//   * normal: process every 1 frame
		//   * fast: doesn't wait at all
		if(game_speed == FAST)
			/*city_process()*/;
		else if(game_speed == NORMAL || game_speed == SLOW)
		{
			if(game_speed == NORMAL 
			||(game_speed == SLOW && n_frame % 3 == 0))
				/*city_process()*/;
			while(SDL_GetTicks() < next_frame)
				SDL_Delay(1);
		}

		n_frame++;
	}
}


void ui_update_video()
{
	SDL_FillRect(screen, NULL, WHITE);
	SDL_Flip(screen);
}
